<?php


namespace App\Logic;


use App\server\RedisServer;
use app\servers\RedisServices;

class SignLogic
{
    /**
     * 签到
     * @param $uid
     * @throws \Exception
     * @yuankai
     */
    public static function sign($params)
    {
        $sign = self::signAdd($params['uid'],$params['date']);//记录数据到redis
        if(!$sign) abort(101,'已经签到过了');
        return true;
    }

    /**
     * 连续签到送积分
     * @param $redis
     * @param $uid
     * @param string $day
     * @return int
     * @yuankai
     */
    public static function getIntegral($uid,$day='')
    {
        $chainDay = self::getField($uid,$day);
        switch ($chainDay){
            case 1 : $integ = 10;break;
            case 2 : $integ = 20;break;
            case 3 : $integ = 30;break;
            case 4 : $integ = 40;break;
            case 5 : $integ = 50;break;
            case 6 : $integ = 60;break;
            case 7<=$chainDay : $integ = 70;break;
        }
        return $integ;
    }

    /**
     * redis签到
     * @param $uid
     * @yuankai
     */
    public static function signAdd($uid,$date)
    {
        $key ='sign'.date('Y_m').'_'.$uid;//设置用户每月签到信息的key值
        $timestamp = strtotime($date);
        $offset =(int)date('d',$timestamp);//偏移量  表示这个月的第几天
        $is_exit =self::getSign($uid,$date);
        if($is_exit == '1') return false;
        //签到
        RedisServices::getInstance()->getRedis()->setBit($key,$offset,true);
        return true;

    }

    /**
     * redis获取签到信息
     * @param $key
     * @param $offset
     * @yuankai
     */
    public static function getSign($uid,$date)
    {
        $key ='sign'.date('Y_m').'_'.$uid;//设置用户每月签到信息的key值
        $timestamp = strtotime($date);
        $offset =(int)date('d',$timestamp);//偏移量  表示这个月的第几天
        return RedisServices::getInstance()->getRedis()->getbit($key,$offset); //
    }

    /**
     * redsi获取签到天数
     * @param $key
     * @return mixed
     * @yuankai
     */
    public static function getSignDay($uid,$date)
    {
        $timestamp = strtotime($date);
        $yearMonth = date('Y_m',$timestamp);
        $key ='sign'.$yearMonth.'_'.$uid;//设置用户每月签到信息的key值
        $count = RedisServices::getInstance()->getRedis()->bitcount($key);
        return $count;
    }

    /**
     * redis查看连续签到天数
     * @param $uid
     * @yuankai
     */
    public static function getField($uid,$date='')
    {
        if($date == '') $date = date('Y-m-d');//如果不传时间默认是今天
        $key ='sign'.date('Y_m').'_'.$uid;//设置用户每月签到信息的key值
        $timestamp = strtotime($date);//获取时间戳
        $day = (int)date('d',$timestamp);//获取当前天数
        $offset = 'u'.$day; //获取查询天数
        $arr = RedisServices::getInstance()->getRedis()->bitfield($key,'GET',$offset,1)[0]; //得到十进制本月签到信息
        $detail = decbin($arr);
        $count = 0;
        for($i=strlen($detail)-1;$i>=0;$i--){
            if($detail[$i] == 1){
                $count++;
            }else{
                break;
            }
        }
        return $count;
    }
}
